/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extensions.net.example.echo.tcp.server;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import jp.arctos.ursus.extension.net.Config;
import jp.arctos.ursus.extension.net.ServerSocketService;
import jp.arctos.ursus.extension.net.ServerSocketSessionHandler;
import jp.arctos.ursus.thread.RealtimeThreadParameters;

public class TCPEchoServer {

    private void echo() throws Exception {
        SocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 10003);

        // サーバソケットサービス作成
        // スレッドはjavax.realtime.RealtimeThreadのデフォルト
        RealtimeThreadParameters threadParameters = new RealtimeThreadParameters();
        Config config = new Config();
        config.setRealtimeThreadParameters(threadParameters);
        ServerSocketService service = new ServerSocketService(config);

        // 非同期イベントを扱うイベントハンドラを設定
        service.setEventHandler(new ServerSocketEchoServerEventHandler());

        // 待ち受け状態のサーバセッションハンドラを取得
        ServerSocketSessionHandler sessionHandler = service.open(serverAddress);
        System.out.println("Opened.");

        Thread.sleep(60000);

        // 60秒後にセッションをクローズ
        sessionHandler.close();

        // サービスをシャットダウン
        service.shutdown();
    }

    public static void main(String[] args) throws Exception {
        TCPEchoServer server = new TCPEchoServer();
        server.echo();
    }
}
